//
//  posterCollectionView.m
//  timemovie
//
//  Created by Yiqiao on 15/7/24.
//  Copyright (c) 2015年 Yiqiao. All rights reserved.
//

#import "posterCollectionView.h"
#import "postCollectionViewCell.h"
#import "UIViewExt.h"
#import "MObj.h"
#define w [UIScreen mainScreen].bounds.size.width
#define h [UIScreen mainScreen].bounds.size.height
#define navH 64;
#define barH 49;
@implementation posterCollectionView

- (id)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self) {
        self.dataSource = self;
        self.delegate = self;
        [self registerClass:[postCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    }
    return self;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.movieModelArray.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    postCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    MObj *model = _movieModelArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    CGFloat cellWidth = w*3/4;
    return UIEdgeInsetsMake(0, (w-cellWidth)/2, 0, (w-cellWidth)/2);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(w*3/4, self.height);
}

- (void)setMovieModelArray:(NSArray *)movieModelArray{
    _movieModelArray = movieModelArray;
}


- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    CGFloat itemWidth = w*3/4;
    
    CGFloat x = targetContentOffset->x;
    
    NSInteger index = x/itemWidth;
    
    if (index<0) {
        index = 0;
    }
    else if(index>=_movieModelArray.count-1){
    
        index=_movieModelArray.count-1;
    }
    
    targetContentOffset->x = itemWidth*index;
    self.currentIndex = index;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //if middle
    
    if (indexPath.row==self.currentIndex){
    
        postCollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        [cell flipCell];
    }
    else{
    //if side
        [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically  animated:YES];
    }
    self.currentIndex = indexPath.row;
    

}




@end
